package service

import (
	"fmt"
	"go.uber.org/zap"
	"gitee.com/carollia/data-sdk-go/internal"
	"gitee.com/carollia/data-sdk-go/model"
)

type Service struct {
	c *model.Config
	d *internal.DisPatcher
}

func NewService(c *model.Config) (s *Service, err error) {
	s = &Service{c:c}
	defer func() {
		if e := recover(); e != nil {
			Logger.Error("NewService Get Panic Error", zap.Any("error", e))
			return
		}
	}()
	fmt.Println("Config is:", c)
	d, err := internal.NewDisPatcher(c)
	if err != nil {
		Logger.Error("NewDisPatcher Get Error", zap.Any("error", err))
		return
	}
	s.d = d
	err = s.Ping()
	if err != nil {
		Logger.Error("Ping Get Error", zap.Any("error", err))
	}
	return
}


// 用户行为事件
func (s *Service) Action(event, uid string, uidType string ,properties map[string]interface{}) (err error) {
	defer func() {
		if e := recover(); e != nil {
			Logger.Error("s.Action Get Panic Error", zap.Any("error", e))
			return
		}
	}()
	data := &model.Action{
		Type:       TYPE_ACTION,
		Event:      event,
		Uid:        uid,
		UidType:    uidType,
		Properties: properties,
	}
	err = s.d.Dispatch(data)
	return
}

// 设备行为事件
func (s *Service) Device(event, deviceNo, deviceType, deviceName string, properties map[string]interface{}) (err error) {
	defer func() {
		if e := recover(); e != nil {
			Logger.Error("s.Device Get Panic Error", zap.Any("error", e))
			return
		}
	}()
	data := &model.Device{
		Type:       TYPE_DEVICE,
		Event:      event,
		DeviceNo:   deviceNo,
		DeviceType: deviceType,
		DeviceName: deviceName,
		Properties: properties,
	}
	err = s.d.Dispatch(data)
	return
}

// 实体信息
func (s *Service) Entity(entity, entityId string, properties map[string]interface{}) (err error) {
	defer func() {
		if e := recover(); e != nil {
			Logger.Error("s.Entity Get Panic Error", zap.Any("error", e))
			return
		}
	}()
	data := &model.Entity{
		Type:          TYPE_ENTITY,
		Entity:        entity,
		EntityId:      entityId,
		Properties:    properties,
	}
	err = s.d.Dispatch(data)
	return
}

// 用户信息设置
func (s *Service) ProfileSet(uid string, uidType string ,properties map[string]interface{}) (err error) {
	return s.profile(TYPE_PROFILE_SET, uid,uidType, properties)
}

// 创建物品
func (s *Service) ItemSet(itemId, itemType string,name string, price float32, properties map[string]interface{}) (err error) {
	return s.item(TYPE_ITEM_SET, itemId, itemType,name, price, properties)
}

// 删除物品
func (s *Service) ItemDelete(itemId string,itemType string) (err error) {
	return s.item(TYPE_ITEM_DELETE, itemId, itemType,"name", 0.0, nil)
}

// 创建礼包
func (s *Service) BundleSet(bundleId, name string, price float32, items [][]int, properties map[string]interface{}) (err error) {
	return s.bundle(TYPE_BUNDLE_SET, bundleId, name, price, items, properties)
}

// 删除礼包
func (s *Service) BundleDelete(bundleId string) (err error) {
	return s.bundle(TYPE_BUNDLE_DELETE, bundleId, "name", 0.0, [][]int{{0, 0}}, nil)
}